package com.zc.im.common.util;

import cn.hutool.core.net.NetUtil;
import com.zc.im.common.constant.enums.ResultEnum;
import com.zc.im.common.exception.CustomException;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.LinkedHashSet;

/**
 * Project：im
 * Date：2022/4/22
 * Time：15:19
 * Description：ip工具类
 *
 * @author Challen.Zhang
 * @version 1.0
 */
public class IpUtil implements EnvironmentAware {

    private static Environment environment;

    private static final String ip = getLocalInnerIp();

    private static String port;

    private static String addressAndPort;

    public static String getIp() {
        return ip;
    }

    public static String getPort() {
        return port;
    }

    public static String getAddressAndPort() {
        return addressAndPort;
    }

    public void init() {
        port = environment.getProperty("server.port");
        addressAndPort = ip + ":" + port;
    }

    /**
     * 获取本机内网ip
     *
     * @return 本机内网ip
     */
    public static String getLocalInnerIp() {
        final LinkedHashSet<InetAddress> localAddressList = NetUtil.localAddressList(t -> t instanceof Inet4Address);

        for (InetAddress inetAddress : localAddressList) {
            if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
                return inetAddress.getHostAddress();
            }
        }
        throw new CustomException(ResultEnum.INTERNAL_SERVER_ERROR, "未获取到ip");
    }

    @Override
    public void setEnvironment(Environment environment) {
        IpUtil.environment = environment;
        init();
    }
}
